package cn.itsource.exam.service.impl;

import cn.itsource.exam.domain.ClassInfo;
import cn.itsource.exam.domain.LogInfo;
import cn.itsource.exam.domain.Login;
import cn.itsource.exam.domain.TeacherInfo;
import cn.itsource.exam.enums.UserTypeEnum;
import cn.itsource.exam.mapper.ClassInfoMapper;
import cn.itsource.exam.mapper.LoginMapper;
import cn.itsource.exam.mapper.TeacherInfoMapper;
import cn.itsource.exam.mapper.TeacherInfoMapper;
import cn.itsource.exam.query.UserInfoQuery;
import cn.itsource.exam.service.LogInfoService;
import cn.itsource.exam.service.TeacherInfoService;
import cn.itsource.exam.service.TeacherInfoService;
import cn.itsource.exam.util.Md5Helper;
import cn.itsource.exam.util.PageList;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by su on 2020/7/8.
 */
@Service
public class TeacherInfoServiceImpl implements TeacherInfoService {

    @Autowired
    private TeacherInfoMapper teacherInfoMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private RoleServiceImpl roleService;

    /**
     * 增加或修改用户
     * @param user
     * @return
     */
    @Override
    public String modifyUser(TeacherInfo user,String operateuser) {
        try{
            int count = 0;
            Map<String,Object> map = new HashMap<>();
            if(StringUtils.isNotEmpty(user.getPhone())){
                map.put("phone",user.getPhone());
            }
            if(StringUtils.isNotEmpty(user.getIdnumber())){
                map.put("idnumber",user.getIdnumber());
            }
            List<TeacherInfo> list = teacherInfoMapper.selectByMap(map);
            if(user.getId() != null){   // 如果ID不为空说明是修改
                if(list != null && list.size() > 0){
                    for(TeacherInfo userInfo:list){
                        if(!userInfo.getId().equals(user.getId()) && userInfo.getPhone().equals(user.getPhone())){
                            return "该电话已存在!";
                        }
                        if(!userInfo.getId().equals(user.getId()) && userInfo.getIdnumber().equals(user.getIdnumber())){
                            return "该身份证号已存在!";
                        }
                    }
                }
                user.setModifytime(new Date());
                count = teacherInfoMapper.updateById(user);
                if(count > 0){
                    logInfoService.addLogInfo(new LogInfo(UserTypeEnum.TEACHER.getId(),"修改"+user.getName()+"信息",operateuser));
                }
            }else{
                if(list != null && list.size() > 0){
                    for(TeacherInfo userInfo:list){
                        if(userInfo.getPhone().equals(user.getPhone())){
                            return "该电话已存在!";
                        }
                        if(userInfo.getIdnumber().equals(user.getIdnumber())){
                            return "该身份证号已存在!";
                        }
                    }
                }
                user.setAddtime(new Date());
                user.setStatus(0);
                // 操作login表
                Login login = operateLogin(user);
                //主表给次表赋值id
                user.setId(login.getId());
                /******login表操作结束*****/
                count = teacherInfoMapper.insert(user);
                roleService.addUserRole(user.getId(),UserTypeEnum.TEACHER.getId()+"");
                if(count > 0){
                    logInfoService.addLogInfo(new LogInfo(UserTypeEnum.TEACHER.getId(),"新增"+user.getName()+"信息",operateuser));
                }
            }
            return count > 0 ? "":"操作失败";
        }catch (Exception e){
            e.printStackTrace();
            return "程序错误";
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public String delUser(Long id,String operateuser) {
        TeacherInfo user = teacherInfoMapper.selectById(id);
        if(user == null || user.getStatus() != 0){
            return "用户不存在!";
        }
        user.setStatus(1);
        user.setModifytime(new Date());
        int count = teacherInfoMapper.updateById(user);
        if(count > 0){
            logInfoService.addLogInfo(new LogInfo(UserTypeEnum.TEACHER.getId(),"删除"+user.getName()+"信息",operateuser));
        }
        return count > 0 ? "":"操作失败";
    }

    /**
     * 根据主键查询用户
     * @param id
     * @return
     */
    @Override
    public TeacherInfo getUserById(Long id) {
        TeacherInfo userInfo = teacherInfoMapper.selectById(id);
        if(userInfo != null && userInfo.getStatus() == 0){
            return userInfo;
        }
        return null;
    }

    /**
     * 分页查询用户
     * @param paramIn
     * @return
     */
    @Override
    public PageList<TeacherInfo> getUserList(UserInfoQuery paramIn) {
        Integer count = teacherInfoMapper.countUserList(paramIn);
        if (count == null || count == 0){
            return  new PageList<TeacherInfo>();
        }
        PageList<TeacherInfo> list =  new PageList<TeacherInfo>(count,teacherInfoMapper.selectUserList(paramIn));
        return list;
    }

    @Override
    public String batchDelUser(String ids,String operateuser) {
        if(StringUtils.isEmpty(ids)){
            return "请选择要删除的数据!";
        }
        List<TeacherInfo> list = teacherInfoMapper.selectBatchIds(Arrays.asList(ids.split(",")));
        int count = teacherInfoMapper.batchdel(Arrays.asList(ids.split(",")));
        if(count > 0){
            new Thread(){   // 异步插入日志
                public void run(){
                    for(TeacherInfo user:list){
                        logInfoService.addLogInfo(new LogInfo(UserTypeEnum.TEACHER.getId(),"删除"+user.getName()+"信息",operateuser));
                    }
                }
            }.start();
        }
        return count > 0 ? "":"操作失败";
    }

    @Override
    public List<TeacherInfo> getAllTeacherList() {
        return teacherInfoMapper.getAllTeacherList();
    }

    private Login operateLogin(TeacherInfo user){
        Login login = new Login();
        login.setPassword(Md5Helper.MD5("123456"));
        login.setPhone(user.getPhone());
        login.setName(user.getName());
        login.setStatus("0");
        login.setU_type(UserTypeEnum.TEACHER.getId());

        loginMapper.insert(login);
        return login;
    }
}
